<?php

namespace app\admin\controller;

use think\Lang;

/**
 *服务人员等级说明
 */
class Fupersonal extends AdminControl
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/fupersonal.lang.php');
    }

    /**
     * 列表
     * @return mixed
     */
    public function index()
    {
        $model = model('fupersonal');
        $condition = [];
        /**
         * 检索条件
         */
        if (!empty(trim(input('search_phone')))) {
            $condition['ds_fuwu_personal.phone'] = array('like', '%' . trim(input('search_phone')) . '%');
        }
        if (!empty(trim(input('search_code')))) {
            $condition['ds_fuwu_personal.code'] = array('like', '%' . trim(input('search_code')) . '%');
        }
        if (!empty(trim(input('search_skillid')))) {
            $condition['ds_fuwu_personal.skillid'] = trim(input('search_skillid'));
        }
        if (!empty(trim(input('search_grade')))) {
            $condition['ds_fuwu_personal.gradeid'] = trim(input('search_grade'));
        }
        //
        if (!empty(trim(input('search_prevcode')))) {
            $condition['ds_fuwu_personal.prevcode'] = array('like', '%' . trim(input('search_prevcode')) . '%');
        }
        if (!empty(trim(input('search_admin_name')))) {
            $condition['ds_fuwu_personal.admin_name'] = array('like', '%' . trim(input('search_admin_name')) . '%');
        }
        if (!empty(trim(input('search_status')))) {
            $status = input('search_status');
            if ($status == 2) {
                $status = 0;
            }
            $condition['ds_fuwu_personal.status'] = $status;
        }

        //时间
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_fuwu_personal.created_at'] = array('between', array($query_start_time, $query_end_time));
        }

        $data = $model->getList($condition, 'ds_fuwu_personal.*,s.name as skillname,g.name as gradename', 10);
           foreach($data as $k=>$v){
           if($v['prevtype'] ==2 ||$v['prevtype'] ==3 ){
               $member_info = db('member')->alias('m')
                   ->join('store s','m.member_id = s.member_id')
                   ->where('m.invite_code',$v['prevcode'])->find();
               if($member_info){
                  $data[$k]['prevcode'] =  $member_info['store_name'];
               }
           }else if($v['prevtype'] ==4){
               $fuwu_info = db('fuwu_personal')->where('code',$v['prevcode'])->find();
               if($fuwu_info){
                   $data[$k]['prevcode'] =  $fuwu_info['name'] ? $fuwu_info['name'] : $fuwu_info['phone'];
               }
           }else if($v['prevtype'] ==1){
               $data[$k]['prevcode'] =  '总平台';
           }else{
               $data[$k]['prevcode'] =  '本人注册';
           }

         }

        $this->assign('data', $data);
        $skillArr = model('fuskill')->getList(['status' => 1], 'id,name');
        $gradeArr = model('fugrade')->getList(['status' => 1], 'id,name', 0, 'id asc');
        $this->assign('skillArr', $skillArr);
        $this->assign('gradeArr', $gradeArr);
        $this->assign('showpage', $model->page_info->render());
        $this->assign('search_phone', trim(input('search_phone')));
        $this->assign('search_grade', trim(input('search_grade')));
        $this->assign('search_code', trim(input('search_code')));
        $this->assign('search_skillid', trim(input('search_skillid')));
        $this->assign('search_prevcode', trim(input('search_prevcode')));
        $this->assign('search_admin_name', trim(input('search_admin_name')));
        $this->assign('search_status', trim(input('search_status')));
        $this->assign('is_super_admin', session('admin_is_super'));
        $this->setAdminCurItem('index');
        return $this->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        $model = model('fupersonal');
        if (request()->isPost()) {
            $membermodel = model('member');
            $_POST['code'] = $membermodel->createInviteCode();
            $validate = validate('fupersonal');
            if (!$validate->scene('add')->check($_POST)) {
                $this->error($validate->getError());
            }
            /**
             * 获取邀请人id
             */
            $data2 = $model->getMember($_POST['prevcode']);
            unset($_POST['quren_password']);
            unset($_POST['file']);
            $_POST['password'] = md5($_POST['password']);
            $_POST['login_num'] = 0;
            $_POST['prev'] = $previd = $data2['prev'];
            $_POST['prevtype'] = $prevtype = $data2['prevtype'];

            $avtar = empty($_POST['avtar']) ? 'http://33wang.douyinhot.com/46f5b202003131520417317.png' : $_POST['avtar'];
            #生成二维码
            $result = scerweima1('https://www.baidu.com', 'fuwu_' . $_POST['code'], $avtar);

            #生成海报
            #生成海报
            $config = array(
                'text' => array(
                    array(
                        'text' => $_POST['code'],
                        'left' => 480,
                        'top' => 610,
                        'fontPath' => 'code/SIMYOU.TTF',     //字体文件
                        'fontSize' => 45,             //字号
                        'fontColor' => '0,0,0',       //字体颜色
                        'angle' => 0,
                    )
                ),
                'image' => array(
                    array(
                        'url' => $result['code'],     //二维码资源
                        'stream' => 0,
                        'left' => 330,
                        'top' => 916,
                        'right' => 0,
                        'bottom' => 0,
                        'width' => 478,
                        'height' => 478,
                        'opacity' => 100
                    )
                ),
                'background' => 'http://33wang.douyinhot.com/f07e9202003151744241290.png'          //背景图
            );
            $filename = 'code/' . time() . '.jpg';
            createPoster($config, $result['code']);

            #纯二维码
            $_POST['fuwu_img_code'] = "http://three.douyinhot.com/" . $result['img_code'];

            #海报二维码
            $_POST['fuwu_code'] = "https://three.douyinhot.com/" . $result['code'];
            if ($model->add($_POST)) {

                #创建极光im用户账号
                $post = [
                    'username' => 'fuwu' . $_POST['phone'],
                    'password' => $_POST['password'],
                    'nickname' => $_POST['phone'],
                    'avatar' => $avtar,
                    'signature' => '',
                ];

                JmRegist($post);



                if ($previd && $prevtype != 2) {
                    $boo = $model->updateYue($previd, $prevtype);
                    if ($boo) {
                        //                        $this->log(lang('ds_edit') . '用户积分' . '[' . input('post.name') . ']', 1);
                        dsLayerOpenSuccess(lang('ds_common_save_succ'));
                    } else {
                        $this->error('添加成功,修改积分失败');
                    }
                } else {
                    $this->log(lang('ds_add') . lang('fuwu_personal_D') . '[' . input('post.name') . ']', 1);
                    dsLayerOpenSuccess(lang('ds_common_save_succ'));
                }
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $data = [
                'id' => '',
                //                'code'=>$code,
                'prevcode' => '',
                'skillid' => '',
                'phone' => '',
                'password' => '',
                'avtar' => '',
                'sex' => '',
                'birthday' => date('Y-m-d', time()),
                'address' => "",
                'kouhao' => '',
                'gradeid' => '',
                'admin_id' => session('admin_id'),
                'admin_name' => session('admin_name'),
                'status' => 1,
                'startweek' => 1,
                'endweek' => 7,
                'starttime' => '09:00',
                'endtime' => '20:00',
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
            ];
            $skillArr = model('fuskill')->getList(['status' => 1], 'id,name');
            $gradeArr = model('fugrade')->getList(['status' => 1], 'id,name', 0, 'id asc');
            $weekArr = getWeek();
            $timeArr = getTime();
            $this->setAdminCurItem('add');
            $this->assign('skillArr', $skillArr);
            $this->assign('gradeArr', $gradeArr);
            $this->assign('weekArr', $weekArr);
            $this->assign('timeArr', $timeArr);
            $this->assign('data', $data);
            return $this->fetch('form');
        }
    }

    /**
     * 修改
     */
    public function edit()
    {
        $model = model('fupersonal');
        if (request()->isPost()) {
            $validate = validate('fupersonal');
            $_POST['updated_at'] = date('Y-m-d H:i:s', time());
            if (!$validate->scene('edit')->check($_POST)) {
                $this->error($validate->getError());
            }
            if (strlen($_POST['password'])) {
                $_POST['password'] = md5($_POST['password']);
            } else {
                unset($_POST['password']);
            }
            unset($_POST['quren_password']);
            unset($_POST['file']);

            //获取更换的服务编码
            $prev = $model->getMember($_POST['prevcode']);
            $_POST['prevcode'] = $_POST['prevcode'];
            $_POST['prev'] = $prev['prev'];
            $_POST['prevtype'] = $prev['prevtype'];

            if ($res = $model->edit(['id' => $_POST['id']], $_POST)) {
                #极光im更换头像
                $service_info = db('fuwu_personal')->where(['id' => $_POST['id']])->find();
                $file_data['file_name'] = $service_info['avtar'];
                updateUserAvtar($file_data,'fuwu'.$service_info['phone']);


                $this->log(lang('ds_update') . lang('fuwu_personal_D') . '[' . input('post.name') . ']', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->log(lang('ds_update') . lang('fuwu_personal_D') . '[' . input('post.name') . ']', 0);
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $data = $model->info(['id' => input('id')]);
            $skillArr = model('fuskill')->getList(['status' => 1], 'id,name');
            $gradeArr = model('fugrade')->getList(['status' => 1], 'id,name', 0, 'id asc');
            $weekArr = getWeek();
            $timeArr = getTime();
            $this->assign('weekArr', $weekArr);
            $this->assign('timeArr', $timeArr);
            $this->setAdminCurItem('edit');
            $this->assign('skillArr', $skillArr);
            $this->assign('gradeArr', $gradeArr);
            $this->assign('data', $data);
            return $this->fetch('edit');
        }
    }

    /**
     * 修改状态
     */
    public function edit_status()
    {
        $model = model('fupersonal');
        $condition['id'] = input('id');
        $data[input('column')] = input('value');
        $info = $model->edit($condition, $data);
        if ($info) {
            $this->log(lang('ds_edit') . lang('fuwu_personal_D') . '[ID:' . intval(input('id')) . ')', 1);
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            $this->log(lang('ds_edit') . lang('fuwu_personal_D') . '[ID:' . intval(input('id')) . ')', 0);
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        $ids = trim(input('id'));
        $idArr = ds_delete_param($ids);
        if ($idArr == FALSE) {
            $this->log(lang('ds_del') . lang('fuwu_personal_D') . '[ID:' . $ids . ']', 0);
            ds_json_encode(10001, lang('param_error'));
        }
        $model = model('fupersonal');
        $model->del(array('id' => array('in', implode(',', $idArr))));
        $this->log(lang('ds_del') . lang('fuwu_personal_D') . '[ID:' . $ids . ']', 1);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    /**
     * ajax
     */
    public function ajax()
    {
        $model = model('fupersonal');
        switch (input('branch')) {
            case 'check_phone':
                $condition['phone'] = trim(input('phone'));
                $condition['id'] = ['neq', input('id')];
                $data = $model->getList($condition, 'id');
                if (empty($data)) {
                    exit('true');
                } else {
                    exit('false');
                }
            case 'check_week':
                $startweek = trim(input('startweek'));
                $endweek = trim(input('endweek'));
                if ($startweek >= $endweek) {
                    exit('false');
                }
                exit('true');
            case 'check_time':
                $starttime = trim(input('starttime'));
                $endtime = trim(input('endtime'));
                $startArr = explode(':', $starttime);
                $endArr  = explode(':', $endtime);
                if ($startArr[0] >= $endArr[0]) {
                    exit('false');
                }
                exit('true');
            case 'check_money':
                $money = input('money');
                if (!$money) {
                    exit('false');
                }
                if ($money == '0.00') {
                    exit('false');
                }
                exit('true');
        }
    }
    /**
     * 修改余额
     */
    public function updateYu()
    {
        $model = model('fupersonal');
        if (request()->isPost()) {
            if (($res = $model->edit(['id' => $_POST['id']], $_POST)) !== false) {
                $this->log(lang('ds_update') . lang('fuwu_personal_D') . '[' . input('post.name') . '余额]', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->log(lang('ds_update') . lang('fuwu_personal_D') . '[' . input('post.name') . '余额]', 0);
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $data = $model->info(['id' => input('id')]);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    /**
     * 实名认证
     * @return mixed
     */
    public function shiming()
    {
        $model = model('fupersonal');
        if (request()->isPost()) {
            $_POST['updated_at'] = date('Y-m-d H:i:s', time());
            $_POST['status_admin_id'] = session('admin_id');
            $_POST['status_admin_name'] = session('admin_name');
            $_POST['status_at'] = date('Y-m-d H:i:s', time());
            unset($_POST['file']);
            if ($res = $model->edit(['id' => $_POST['id']], $_POST)) {
                $this->log('实名认证' . lang('fuwu_personal_D') . '[' . input('post.id') . ']', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->log('实名认证' . lang('fuwu_personal_D') . '[' . input('post.id') . ']', 0);
                $this->error(lang('ds_common_save_fail'));
            }
        } else {

            $data = $model->info(['id' => input('id')]);
            $this->setAdminCurItem('shiming');
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    /**
     * 添加技能
     * @return int|String
     */
    public function addjineng()
    {
        if (request()->isPost()) {


            $model = model('fujineng');
            $class_id = input('class_id') ? input('class_id') : '';
            $catetwo = model('goodsclass')->getGoodsclassInfoById($class_id);

            $data = [
                'fuwuid' => $_POST['id'],
                'brandid' => ',' . $_POST['b_id'] . ',',
                'anzhuang' => $_POST['anzhuang'],
                'weixiu' => $_POST['weixiu'],
                'baoyang' => $_POST['baoyang'],
                'catrthree' => $_POST['class_id'],
                'catetwo' => $catetwo['gc_parent_id'],
                'cateone' => $_POST['gcategory'],
                'status' => $_POST['status'],
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
                'status_admin_id' => session('admin_id'),
                'status_admin_name' => session('admin_name'),
                'status_at' => date('Y-m-d H:i:s', time()),
            ];

            
            $data['brandid'] = trim($data['brandid'],",");
            $b_ids = explode(",",$data['brandid']);

            $skill_list =db('fuwu_personal_jineng')->where(['catrthree'=>$_POST['class_id'],'fuwuid'=>$_POST['id']])->select();

            if($skill_list){
                foreach($skill_list as $key => $value){
                    $list_brandid = trim($value['brandid'],",");
                    $list_b_ids = explode(",",$list_brandid);
                    $new_array = array_merge($b_ids,$list_b_ids);
                    if(count($new_array) != count(array_unique($new_array))){
                        dsLayerOpenSuccess('分类和品牌已重复');
                    }

                }
            }

            foreach($b_ids as $key => $b_id){

                $data['brandid'] = $b_id;
               // $data['b_name'] = $b_names[$key];

                $bool = $model->add($data);

            }

            if ($bool) {
                $this->log(lang('ds_add') . lang('fuwu_personal_D') .  '技能[' . input('post.id') . ']', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list', $brand_list);
            // 一级商品分类
            $gc_list = model('goodsclass')->getGoodsclassListByParentId(0);
            $this->assign('gc_list', $gc_list);
            $this->assign('id', input('id'));
            //             $this->setAdminCurItem('addjineng');
            return $this->fetch('addjineng');
        }
    }

    /**
     * 技能列表
     * @return int|String
     */
    public function jineng()
    {
        $model = model('fujineng');
        $condition = [];
        $condition['fuwuid']  = input('id');
        /**
         * 检索条件
         */
        $data = $model->getList($condition, 'ds_fuwu_personal_jineng.*,g.gc_name as cateonename,g2.gc_name as catetwoname,g3.gc_name as catethreename,b.brand_name', 10);
        $this->assign('data', $data);
        $this->assign('id', input('id'));
        $this->assign('showpage', $model->page_info->render());
        $this->setAdminCurItem('jineng');
        return $this->fetch();
    }

    /**
     * 技能删除
     * @return int|String
     */
    public function jineng_del()
    {
        $ids = trim(input('id'));
        $idArr = ds_delete_param($ids);
        if ($idArr == FALSE) {
            $this->log(lang('ds_del') . lang('fuwu_personal_D') . '技能[ID:' . $ids . ']', 0);
            ds_json_encode(10001, lang('param_error'));
        }
        $model = model('Fujineng');
        $model->del(array('id' => array('in', implode(',', $idArr))));
        $this->log(lang('ds_del') . lang('fuwu_personal_D') . '技能[ID:' . $ids . ']', 1);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    /**
     * 区域删除
     */
    public function address_del()
    {
        $ids = trim(input('id'));
        $idArr = ds_delete_param($ids);
        if ($idArr == FALSE) {
            $this->log(lang('ds_del') . lang('fuwu_personal_D') . '技能[ID:' . $ids . ']', 0);
            ds_json_encode(10001, lang('param_error'));
        }
        $model = model('fuaddress');
        $model->del(array('id' => array('in', implode(',', $idArr))));
        $this->log(lang('ds_del') . lang('fuwu_personal_D') . '技能[ID:' . $ids . ']', 1);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    /*
     * 图片上传
    */
    public function ajax_upload()
    {
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $file_name = input('post.name');
            $upload_info = upload_qiniu('file');
            $upload_info['data'] = $upload_info['http'] . '/' . $upload_info['data'];
            return $upload_info;
        } else {
            return $data['msg'] = 0;
        }
    }

    /**
     * 详情
     */
    public function view()
    {
        $model = model('fupersonal');
        $data = $model->info(['id' => input('id')]);
        $skillArr = model('fuskill')->info(['status' => 1, 'id' => $data['skillid']], 'id,name');
        $gradeArr = model('fugrade')->info(['status' => 1, 'id' => $data['gradeid']], 'id,name');
        $weekArr = getWeek();
        $this->assign('weekArr', $weekArr);
        $this->assign('skillArr', $skillArr);
        $this->assign('gradeArr', $gradeArr);
        $this->assign('data', $data);
        $this->setAdminCurItem('view');
        return $this->fetch();
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => lang('ds_manage'),
                'url' => url('Fupersonal/index'),
            ),
            array(
                'name' => 'add',
                'text' => lang('ds_add'),
                'url' => url('Fupersonal/add'),
            ),
        );
        if (request()->action() == 'edit') {
            $menu_array[] = array(
                'name' => 'edit',
                'text' => lang('ds_edit'),
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'shiming') {
            $menu_array[] = array(
                'name' => 'shiming',
                'text' => '实名认证',
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'addjineng') {
            $menu_array[] = array(
                'name' => 'addjineng',
                'text' => '添加技能',
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'jineng') {
            $menu_array[] = array(
                'name' => 'jineng',
                'text' => '技能列表',
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'address') {
            $menu_array[] = array(
                'name' => 'address',
                'text' => '区域列表',
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'view') {
            $menu_array[] = array(
                'name' => 'view',
                'text' => '查看详情',
                'url' => 'javascript:void(0)'
            );
        }
        if (request()->action() == 'address_edit') {
            $menu_array[] = array(
                'name' => 'address_edit',
                'text' => '区域修改',
                'url' => 'javascript:void(0)'
            );
        }
        return $menu_array;
    }
}
